package com.m3958.firstgwt.client.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayInteger;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.JsDate;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.m3958.gwtutil.clientside.client.jso.BaseModelJso;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.widgets.tree.TreeNode;

/**
 * 
 * @author Administrator
 * 
 */


public class XyzJsoUtils {
	
	public static final String addParens(String s){
		if(s.startsWith("(") && s.endsWith("(")){
			return s;
		}else{
			return "(" + s + ")";
		}
		
	}
	
	public static final String[] jsArrayStringToStringArray(JsArrayString jsas){
		String[] sa = new String[jsas.length()];
		for(int i=0;i< jsas.length();i++){
			sa[i] = jsas.get(i);
		}
		return sa;
	}
	
	
	
	public static final RecordList getRecordList(JsArray<? extends JavaScriptObject> jsArray){
		Record[] rs = new Record[jsArray.length()];
		for (int i = 0; i < jsArray.length(); i++) {
			Record r = new Record(jsArray.get(i));
			rs[i] = r;
		}
		return new RecordList(rs);
	}
	
	
	public static final TreeNode[] jsArrayToTreeNode(JsArray<? extends JavaScriptObject> jsArray){
		TreeNode[] tns = new TreeNode[jsArray.length()];
		for (int i = 0; i < jsArray.length(); i++) {
			TreeNode tn = new TreeNode(jsArray.get(i));
			tns[i] = tn;
		}
		return tns;
	}
	
	//注意eval的歧义性，string两侧必须添加括号。
	
	
//	public static final native JsArray<? extends BaseModelJso> getJsArray(String jsonStr)/*-{
//		if(jsonStr.charAt(0) == "("){
//			return eval(jsonStr);
//		}else{
//			return eval("(" + jsonStr + ")");
//		}
//	}-*/;
	
	
	
	public static final native JsArray<? extends BaseModelJso> getJsArray(String jsonStr)/*-{
		var isString = function (object) {
        	if (object == null) return false;
        	if(!object)return false;
            return typeof object == "string";
        };
        
        var regexp = "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:([0-9]{2}))?(\.[0-9]+)?$"
		var patt=new RegExp(regexp);
		
		var ao = null;
		if(jsonStr.charAt(0) == "("){
			ao = eval(jsonStr);
		}else{
			ao = eval("(" + jsonStr + ")");
		}
		if(ao == null)return null;
		var j = 0;
		for(var j = 0;j<ao.length;j++){
			var o = ao[j];
			if(o != null){
			for(var i in o){
				if(isString(o[i]) && patt.test(o[i])){
					var millis = @com.m3958.firstgwt.client.utils.XyzJsoUtils::getMillisStr(Ljava/lang/String;)(o[i]);
					var date = new Date();
					date.setTime(parseInt(millis));
					o[i] = date;
				}
			}
			}
		}
		return ao;
	}-*/;
	
	
	public static native JsArrayInteger getJsArrayInteger(String intAryStr)/*-{
		return eval(intAryStr);
	}-*/;
	
	
	
	public static final native BaseModelJso getBaseModelJso(String jsonStr)/*-{
		var isString = function (object) {
        	if (object == null) return false;
        	if(!object)return false;
            return typeof object == "string";
        };
        
        var regexp = "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:([0-9]{2}))?(\.[0-9]+)?$"
		var patt=new RegExp(regexp);
        
		var o = null;
		if(jsonStr.charAt(0) == "("){
			o =  eval(jsonStr);
		}else{
			o = eval("(" + jsonStr + ")");
		}
		
		if(o != null){
			for(var i in o){
				if(isString(o[i]) && patt.test(o[i])){
					var millis = @com.m3958.firstgwt.client.utils.XyzJsoUtils::getMillisStr(Ljava/lang/String;)(o[i]);
					var date = new Date();
					date.setTime(parseInt(millis));
					o[i] = date;
				}
			}
		}
		return o;
	}-*/;
	
	
	public static JsArray<? extends BaseModelJso> getDataArrayFromResponse(String result){
		return getJsArray(getResultDataString(result));
	}

	public static BaseModelJso getBaseModelJsoFromResponse(String result){
		return getBaseModelJso(getResultDataString(result));
	}
	
	public static String getResultDataString(String response){
		JSONObject jo = JSONParser.parseStrict(response).isObject();
		if(jo.containsKey("response")){
			jo = jo.get("response").isObject();
		}
		String s = jo.get("data").toString();
		return s;
	}
	
    public static native Date getDate(JavaScriptObject elem) /*-{
		return (elem === undefined || elem == null) ? null: @com.m3958.firstgwt.client.utils.XyzJsoUtils::toDate(D)(elem.getTime());
	}-*/;
    
    
	public static Date getDateFromString(String dateStr){
    	if(dateStr == null)return null;
    	String[] str = dateStr.split("T");
    	if(str.length != 2){
    		return null;
    	}
    	
    	String[] ymd = str[0].split("-");
    	String[] hms = str[1].split(":");
    	int y = Integer.parseInt(ymd[0]);
    	int m = Integer.parseInt(ymd[1]);
    	int d = Integer.parseInt(ymd[2]);
    	int h = Integer.parseInt(hms[0]);
    	int mm = Integer.parseInt(hms[1]);
    	int s = Integer.parseInt(hms[2]);
    	JsDate jd = JsDate.create(y, m, d, h, mm, s);
    	return new Date(new Double(jd.getTime()).longValue());

	};
    
    public static Date toDate(double millis) {
    	Date d = new Date((long) millis);
        return d;
    }
    
    public static boolean isIsoDateFormat(String ds){
    	
    	return false;
    }
    
    public static String getMillisStr(String isodateformat){
    	if(isodateformat == null)return null;
    	Date d = getDateFromString(isodateformat);
    	return String.valueOf(d.getTime());
    }
    
/*    
    Type Signature
    Java Type
    Z
    boolean
    B
    byte
    C
    char
    S
    short
    I
    int
    J
    long
    F
    float
    D
    double
    L fully-qualified-class ;
    fully-qualified-class
    [ type
    type[]
    ( arg-types ) ret-type
    method type
    For example, the Java method:

    long f (int n, String s, int[] arr); 
    has the following type signature:

    (ILjava/lang/String;[I)J 
*/    
}
